package com.appoint.buss.service.impl;

import com.appoint.buss.domain.EpiparaAtacInfo;
import com.appoint.buss.domain.EpiparaAtacSeq;
import com.appoint.buss.domain.EpiparaChipInfo;
import com.appoint.buss.mapper.EpiparaAtacInfoMapper;
import com.appoint.buss.mapper.EpiparaAtacSeqMapper;
import com.appoint.buss.service.AsyncAtacSeqService;
import com.appoint.common.exception.ServiceException;
import com.appoint.common.utils.CreateMultipartFile;
import com.appoint.common.utils.StringUtils;
import com.appoint.common.utils.poi.ExcelUtil;
import com.appoint.common.utils.uuid.UUID;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.monitorjbl.xlsx.StreamingReader;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

@Async
@Slf4j
@Service
public class AsyncAtacSeqServiceImpl extends ServiceImpl<EpiparaAtacInfoMapper, EpiparaAtacInfo> implements AsyncAtacSeqService {

    @Value(value = "${epipara.filePath}")
    private String filePath;

    @Resource
    private EpiparaAtacSeqMapper epiparaAtacSeqMapper;

    @Async
    @Override
    public void saveAtacSeq(List<EpiparaAtacSeq> paramList) throws InterruptedException {
        paramList.forEach(info ->{
            String species = info.getSpecies().replace(" ","_");
            String path = species + "/ATAC-seq/" + info.getAccession() + "/10.macs2_called_peaks";
            List<String> fileNames = getFileNames(filePath + path);
            if(CollectionUtils.isEmpty(fileNames)){
                return;
            }
            for (String fileName : fileNames){
                String importFileName = info.getFile().substring(1);
                if(fileName.indexOf(importFileName) > 0){
                    String pathName = filePath + path + "/" + fileName;
                    info.setId(IdWorker.getIdStr());
                    info.setFile(fileName);
                    epiparaAtacSeqMapper.insert(info);
                    try{
                        //初始化响应信息
                        List<EpiparaAtacInfo> list = new ArrayList<>();
                        FileInputStream in = new FileInputStream(pathName);
                        Workbook wk = StreamingReader.builder()
                                .rowCacheSize(100)  //缓存到内存中的行数，默认是10
                                .bufferSize(8192)  //读取资源时，缓存到内存的字节大小，默认是1024
                                .open(in);  //打开资源，必须，可以是InputStream或者是File，注意：只能打开XLSX格式的文件
                        Sheet sheet = wk.getSheetAt(0);
                        //遍历所有的行
                        for (Row row : sheet) {
                            if(row.getRowNum() == 0){
                                continue;
                            }
                            //遍历所有的列
                            EpiparaAtacInfo epiparaAtacInfo = new EpiparaAtacInfo();
                            for (Cell cell : row) {
                                if(cell.getColumnIndex() == 0){
                                    epiparaAtacInfo.setChr(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 1){
                                    epiparaAtacInfo.setStart(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 2){
                                    epiparaAtacInfo.setEnd(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 3){
                                    epiparaAtacInfo.setPeakName(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 4){
                                    epiparaAtacInfo.setScore(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 5){
                                    epiparaAtacInfo.setStrand(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 6){
                                    epiparaAtacInfo.setFoldchange(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 7){
                                    epiparaAtacInfo.setLog10Pvalue(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 8){
                                    epiparaAtacInfo.setLog10Qvalue(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 9){
                                    epiparaAtacInfo.setSummitPosition(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 10){
                                    epiparaAtacInfo.setGeneChr(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 11){
                                    epiparaAtacInfo.setGeneStart(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 12){
                                    epiparaAtacInfo.setGeneEnd(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 13){
                                    epiparaAtacInfo.setGeneId(cell.getStringCellValue ());
                                }
                                if(cell.getColumnIndex() == 14){
                                    epiparaAtacInfo.setGeneName(cell.getStringCellValue ());
                                }
                            }
                            list.add(epiparaAtacInfo);
                            if(list.size()>= 1000){
                                importUser(list, info.getId(),path + "/" + fileName);
                                list.clear();
                            }
                        }
                        if (!CollectionUtils.isEmpty(list)){
                            importUser(list, info.getId(),path + "/" + fileName);
                        }
                    }catch (Exception e){
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    public void importUser(List<EpiparaAtacInfo> list, String id, String fileDownPath) {
        list.forEach(info ->{
            info.setSeqId(id);
            info.setFileDownPath(fileDownPath);
        });
        this.saveBatch(list);
    }

    /**
     * 得到文件名称
     * @param path 路径
     * @return {@link List}<{@link String}>
     */
    private List<String> getFileNames(String path) {
        File file = new File(path);
        List<String> fileNames = new ArrayList<>();
        return getFileNames(file, fileNames);
    }
    /**
     * 得到文件名称
     *
     * @param file      文件
     * @param fileNames 文件名
     * @return {@link List}<{@link String}>
     */
    private List<String> getFileNames(File file, List<String> fileNames) {
        File[] files = file.listFiles();
        for (File f : files) {
            if (f.isDirectory()) {
                getFileNames(f, fileNames);
            } else {
                fileNames.add(f.getName());
            }
        }
        return fileNames;
    }
}
